/*
 DNN Content Builder- sourceforge.net/projects/dnncb
 Copyright (c) 2004-2008
 by Emerson Lopes (emersonlopes@gmail.com)

 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
 documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
 the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
 to permit persons to whom the Software is furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in all copies or substantial portions 
 of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
 TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
 THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
 CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
 DEALINGS IN THE SOFTWARE.
*/

using System;
using System.Collections;
using System.Web.UI.WebControls;
using DotNetNuke.Entities.Portals;
using System.Web.UI.HtmlControls;

namespace DNNContentBuilder.UserControls
{
    /// <summary>
	///		Summary description for WorkflowStringControl.
	/// </summary>
	public class WorkflowControl : System.Web.UI.UserControl
	{
		// for localization
		public const string resource = "~/DesktopModules/DNNContentBuilder/App_LocalResources/WorkflowControl";

		protected LinkButton			btUpdate;
		protected LinkButton			btDelete;
		protected LinkButton			btCancel;

		protected Label				msgTestConn;
		protected HtmlInputHidden	txtWorkflowId;

		private   DotNetNuke.Entities.Users.UserInfo userInfo;
		private   DotNetNuke.Security.Roles.RoleInfo roleInfo;
	    private readonly PortalSettings portal = new PortalSettings();
		private   ArrayList tasks = new ArrayList();

		private readonly WorkflowController wfController = new WorkflowController();
		private readonly TaskOwnerController toController = new TaskOwnerController();
		private readonly TasksController tkController = new TasksController();
		private readonly DotNetNuke.Entities.Users.UserController usrController = new DotNetNuke.Entities.Users.UserController();
		private readonly DotNetNuke.Security.Roles.RoleController roleController = new DotNetNuke.Security.Roles.RoleController();

		private readonly TaskOwnerInfo toInfo	= new TaskOwnerInfo();
		private readonly TasksInfo tkInfo		= new TasksInfo();
		private   WorkflowInfo wfInfo	= new WorkflowInfo();

		public    string txtTitles			= "";
		public    string txtDescriptions	= "";
		public    string txtUsers			= "";
		public    string txtRoles			= "";
		public    int    portalID           = 0;

		protected Panel 		FormPanel;
		protected DataList 	WorkflowList;
		protected LinkButton 	btSearch;
		protected LinkButton 	btNewWorkflow;
		protected HtmlSelect lbTasks;
		protected TextBox 	txtWorkflowTitle;
		protected TextBox 	txtWorkflowDescription;
		protected Panel 		ListPanel;
		protected Literal 	jsScript;

        public WorkflowControl(PortalSettings portal)
        {
            this.portal = portal;
        }

        public PortalSettings Portal
        {
            get { return portal; }
        }

        private void Page_Load(object sender, EventArgs e)
		{
			// Put user code to initialize the page here
			
			portalID = ContextUtil.GetPortalId(this);
			
			if (IsPostBack) 
			{
				this.btDelete.Attributes.Add("onClick", "javascript:return confirm('" + Commons.GetLocalizedString("label_ConfirmDelete", resource) + "')");
			}

			this.btUpdate.Text		= Commons.GetLocalizedString("button_Update", resource);
			this.btDelete.Text		= Commons.GetLocalizedString("button_Delete", resource);
			this.btCancel.Text		= Commons.GetLocalizedString("button_Cancel", resource);
			this.btNewWorkflow.Text	= Commons.GetLocalizedString("button_Create", resource);
			this.btSearch.Text		= Commons.GetLocalizedString("button_Search", resource);

			this.fillList();

			this.btUpdate.Attributes.Add("onClick", "javascript:getTasksValues()");
		}

		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);

			//this.FillddString();
		}
		
		/// <summary>
		///		Required method for Designer support - do not modify
		///		the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.btCancel.Click += new EventHandler(btCancel_Click);
			this.btSearch.Click += new System.EventHandler(this.btSearch_Click);
			this.btUpdate.Click += new System.EventHandler(this.btUpdate_Click);
			this.btDelete.Click += new System.EventHandler(this.btDelete_Click);
			this.WorkflowList.ItemCreated += new System.Web.UI.WebControls.DataListItemEventHandler(this.WorkflowList_ItemCreated);
			this.btNewWorkflow.Click += new System.EventHandler(this.btNewWorkflow_Click);
			this.Load += new System.EventHandler(this.Page_Load);

		}
		#endregion

		private void clearFields() 
		{
			this.txtWorkflowId.Value = "";
			this.txtWorkflowTitle.Text="";
			this.txtWorkflowDescription.Text="";
			this.lbTasks.Items.Clear();
			this.FormPanel.Visible = false;
			this.btDelete.Visible = false;
			this.ListPanel.Visible = true;
		}

		private void fillList() 
		{
			this.WorkflowList.DataSource = (ICollection)wfController.GetAllWorkflows();
			this.WorkflowList.DataBind();

			btDelete.Visible = false;
		}

		private void WorkflowList_ItemCreated(object sender, DataListItemEventArgs e) 
		{ 
			ListItemType elemType = e.Item.ItemType;

			if ((elemType == ListItemType.Item) || (elemType == ListItemType.AlternatingItem))
			{ 
				ImageButton imgButton = (ImageButton) e.Item.FindControl("btWorkflowSelected"); 
				imgButton.Click += btWorkflowSelected_OnClick; 
			}  
		}

		private void btWorkflowSelected_OnClick(object sender, System.Web.UI.ImageClickEventArgs e)
		{
			ImageButton btWorkflowSelected = (ImageButton)sender;

			wfInfo = (WorkflowInfo)wfController.GetItem(Int32.Parse(btWorkflowSelected.CommandArgument));

			this.ListPanel.Visible = false;
			this.FormPanel.Visible = true;

			btDelete.Visible = true;

			this.txtWorkflowTitle.Text = wfInfo.Title;
			this.txtWorkflowDescription.Text = wfInfo.Description;

			tasks = this.tkController.GetTasksByWorkflow(wfInfo.WorkflowId);

			txtUsers = "";
			txtRoles = "";
			txtTitles = "";
			txtDescriptions = "";

			foreach (TasksInfo taskInfo in tasks) 
			{
				txtTitles = txtTitles + taskInfo.Title + "^";
				txtDescriptions = txtDescriptions + taskInfo.Description + "^";

				ArrayList owners = toController.TaskOwnerGetTaskOwners(taskInfo.TaskId);

				foreach (TaskOwnerInfo taskOwner in owners) 
				{
					if (taskOwner.OwnerType == "U")  //todo: create enum for this...
					{
						userInfo = usrController.GetUser(ContextUtil.GetPortalId(this), taskOwner.OwnerId);

						this.txtUsers = txtUsers + userInfo.Username + ",";
					} 
					else 
					{
						roleInfo = roleController.GetRole(taskOwner.OwnerId, ContextUtil.GetPortalId(this));

						this.txtRoles = txtRoles + roleInfo.RoleName + ",";
					}
				}
				this.txtUsers = txtUsers + "^";
				this.txtRoles = txtRoles + "^";
			}

			//replacing extra ,^ by ^
			txtTitles = txtTitles.Replace(",^","^");
			txtDescriptions = txtDescriptions.Replace(",^","^");
			txtUsers = txtUsers.Replace(",^","^");
			txtRoles = txtRoles.Replace(",^","^");

			//removing extra ^
			txtUsers = txtUsers.Remove(txtUsers.Length - 1, 1);
			txtRoles = txtRoles.Remove(txtRoles.Length - 1, 1);
			txtTitles = txtTitles.Remove(txtTitles.Length - 1, 1);
			txtDescriptions = txtDescriptions.Remove(txtDescriptions.Length - 1, 1);

			this.lbTasks.DataSource = tasks;
			this.lbTasks.DataTextField = "Title";
			this.lbTasks.DataValueField = "Title";
			this.lbTasks.DataBind();

			this.txtWorkflowId.Value = wfInfo.WorkflowId.ToString();

			this.jsScript.Text = "setTasksValues();\n";
		}

		private void btNewWorkflow_Click(object sender, EventArgs e)
		{
			this.clearFields();
			this.ListPanel.Visible = false;
			this.FormPanel.Visible = true;
		}

		private void btUpdate_Click(object sender, EventArgs e)
		{
			string[] taskTitle			= Request.Form.Get("txtTaskTitle").Split('^');
			string[] taskDescription	= Request.Form.Get("txtTaskDescription").Split('^');
			string[] taskUsers			= Request.Form.Get("txtUsers").Split('^');
			string[] taskRoles			= Request.Form.Get("txtRoles").Split('^');

			wfInfo.Title = this.txtWorkflowTitle.Text.Replace("^","");
			wfInfo.Description = DotNetNuke.Common.Utilities.HtmlUtils.StripTags(this.txtWorkflowDescription.Text, true).Replace("^","");

			int workflowId;

			if (this.txtWorkflowId.Value == "") 
			{
				workflowId = wfController.Add(wfInfo);
			} else {
				wfInfo.WorkflowId = Int32.Parse(this.txtWorkflowId.Value);
				wfController.Update(wfInfo);
				tkController.DeleteWorkflowTasks(wfInfo.WorkflowId);
				workflowId = Int32.Parse(this.txtWorkflowId.Value);
			}

			//(re)creating tasks

			for(int loop = 0;loop<taskTitle.Length;loop++) 
			{
				tkInfo.TaskOrder	= loop;
				tkInfo.Title		= DotNetNuke.Common.Utilities.HtmlUtils.StripTags(taskTitle[loop],true).Replace("^","");
				tkInfo.Description	= DotNetNuke.Common.Utilities.HtmlUtils.StripTags(taskDescription[loop],true).Replace("^","");
				tkInfo.WorkflowId	= workflowId;

				int taskId = tkController.Add(tkInfo);

				string[] users = taskUsers[loop].Split(',');
				//setting users
				for(int index = 0;index < users.Length;index++) 
				{
					if (users[index] != "") 
					{
						userInfo = DotNetNuke.Entities.Users.UserController.GetUserByName(ContextUtil.GetPortalId(this),users[index]);

					    if (toController != null) toController.Add(toInfo);
					    if (userInfo != null) {
							toInfo.OwnerId = userInfo.UserID;
							toInfo.OwnerType = "U";
							toInfo.TaskId = taskId;
					    }
					}
				}

				string[] roles = taskRoles[loop].Split(',');
				//setting roles
				for(int index = 0;index < roles.Length;index++) 
				{
					if (roles[index] != "") 
					{
						roleInfo = roleController.GetRoleByName(ContextUtil.GetPortalId(this), roles[index]);

						toInfo.OwnerId = roleInfo.RoleID;
						toInfo.OwnerType = "R";
						toInfo.TaskId = taskId;

					    if (toController != null) toController.Add(toInfo);
					}
				}
			}

			this.clearFields();

			Response.Redirect(DotNetNuke.Common.Globals.NavigateURL(), true);
		}

		private void btSearch_Click(object sender, EventArgs e)
		{
			this.clearFields();

			//Response.Redirect(DotNetNuke.Common.Globals.NavigateURL(ContextUtil.GetTabId(this)), true);
		}

		private void btDelete_Click(object sender, EventArgs e)
		{
			tkController.DeleteWorkflowTasks(wfInfo.WorkflowId);

			try 
			{
				wfController.Delete(Int32.Parse(this.txtWorkflowId.Value));
			}
			catch (Exception)
			{
			    //TODO: To show some error message like: It's impossible to delete that workflow due dependencies
			}

			this.clearFields();

			Response.Redirect(DotNetNuke.Common.Globals.NavigateURL(), true);

		}

		private void btCancel_Click(object sender, EventArgs e)
		{
			this.clearFields();
			Response.Redirect(DotNetNuke.Common.Globals.NavigateURL(), true);
		}
	}
}
